# $Id: decorators.py 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

__version__ = "$Revision: 7557b5d4d82b $"
__author__ = "$Author: pgurumur $"

from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, Http404
from django.utils.functional import wraps
from django.contrib.auth.models import User

from aptools.utils import http

def is_authenticated(func, redirect = None):
   def wrapper(request, *args, **kwargs):
      if request.user.is_authenticated():
         retval = HttpResponseRedirect("/django/djanet/mobile/")
      else:
         retval = func(request, *args, **kwargs)

      return retval

   return wraps(func)(wrapper)

def mlogin_required(func):
   def wrapper(request, *args, **kwargs):
      if request.user.is_authenticated():
         retval = func(request, *args, **kwargs)
      else:
         return HttpResponseRedirect("/django/djanet/mobile/login/")

      return retval

   return wraps(func)(wrapper)

def superuser_required(func):
   def wrapper(request, *args, **kwargs):
      retval = None
      if request.user.is_authenticated():
         user = User.objects.get(username = str(request.user))
         if user.is_superuser:
            retval = func(request, *args, **kwargs)
         else:
            raise Http404
      return retval

   return wraps(func)(wrapper)

def json_response(func):
   def wrapper(request, *args):
      retval = None
      context = func(request, *args)
      if context:
         retval = http.JSONResponse(context)

      return retval

   return wraps(func)(wrapper)
